package com.pearl.study05.demo.validation;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import org.camunda.bpm.engine.ManagementService;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.ProcessEngines;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.impl.ProcessEngineImpl;
import org.camunda.bpm.engine.impl.TaskServiceImpl;
import org.camunda.bpm.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.camunda.bpm.model.bpmn.instance.ConditionExpression;
import org.camunda.bpm.model.bpmn.instance.ExclusiveGateway;
import org.camunda.bpm.model.bpmn.instance.SequenceFlow;
import org.camunda.bpm.model.bpmn.instance.UserTask;
import org.camunda.bpm.model.xml.validation.ModelElementValidator;
import org.camunda.bpm.model.xml.validation.ValidationResultCollector;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author TD
 * @version 1.0
 * @date 2024/1/15
 */
public class ExclusiveGatewayValidator implements ModelElementValidator<ExclusiveGateway> {
    @Override
    public Class<ExclusiveGateway> getElementType() {
        return ExclusiveGateway.class;
    }

    @Override
    public void validate(ExclusiveGateway exclusiveGateway, ValidationResultCollector validationResultCollector) {
        ManagementService managementService;
        ProcessEngineImpl processEngineConfiguration = ((ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine());
        ProcessEngineConfigurationImpl processEngineConfiguration1 = processEngineConfiguration.getProcessEngineConfiguration();
        // 获取命令服务
        Collection<SequenceFlow> outgoing = exclusiveGateway.getOutgoing();  // 流入分支
        // 必须包含流入分支
        if (outgoing.isEmpty()) {
            validationResultCollector.addError(500, StrUtil.format("排他网关【{}】流入分支不能为空", exclusiveGateway.getName()));
        }
        // 不能包含多条默认分支
        int defaultSequenceFlow = 0;
        for (SequenceFlow sequenceFlow : outgoing) {
            ConditionExpression conditionExpression = sequenceFlow.getConditionExpression();
            // String conditionStr = conditionExpression.getTextContent(); // 表达式
            if (ObjectUtil.isNull(conditionExpression)) {
                // 没有表达式 说明是默认分支
                defaultSequenceFlow += 1;
            }
        }
        if (defaultSequenceFlow > 1) {
            validationResultCollector.addError(500, StrUtil.format("排他网关【{}】不能包含多个默认分支", exclusiveGateway.getName()));
        }
    }
}
